//
//  XWJReadStateView.swift
//  DZMeBookRead
//
//  Created by fox on 2017/10/13.
//  Copyright © 2017年 DZM. All rights reserved.
//

import UIKit

class XWJReadStateView: UIView {

    /// 🔋
    var batteryView:XWJBatteryView = XWJBatteryView()
    var timeLabel = UILabel()
    var pageLabl = UILabel()
    var pageString:String = "" {
        didSet {
            pageLabl.text = pageString
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        batteryView.frame = CGRect.init(x: 12, y: 10, width: 25, height: 10)
        timeLabel.frame = CGRect.init(x: ScreenWidth - 60, y: 0, width: 50, height: 30)
        pageLabl.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 20)
    }


    func setupUI() {
        batteryView.batteryLevel = CGFloat(UIDevice.current.batteryLevel)
        addSubview(batteryView)

        UIDevice.current.isBatteryMonitoringEnabled = true
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil, queue: OperationQueue.main) { (notification) in
            let level = UIDevice.current.batteryLevel
            self.batteryView.batteryLevel = CGFloat(level)
    }

        addSubview(pageLabl)
        pageLabl.font = UIFont.systemFont(ofSize: 14)
        pageLabl.textAlignment = .center
        pageLabl.backgroundColor = UIColor.clear

        addSubview(timeLabel)
        timeLabel.font = UIFont.systemFont(ofSize: 14)
        timeLabel.textAlignment = .center

        timeLabel.text = getCurrentTime()

        // Fallback on earlier versions
        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(getTime(time:)), userInfo: nil, repeats: true)
}

    @objc func getTime(time:Timer){
        self.timeLabel.text = self.getCurrentTime()
    }

    func getCurrentTime()->String{
        let calendar = NSCalendar.current as NSCalendar
        let components = calendar.components([NSCalendar.Unit.hour,NSCalendar.Unit.minute], from: Date())
        let hour = components.hour
        let minute = components.minute
      return  String.init(format: "%02d:%02d", hour ?? 00,minute ?? 00)
//        return "\(hour ?? 00):\(minute ?? 00)"
    }

}
